#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include <time.h>
#include <stdlib.h>

osThreadId_t task_1_id;
osThreadId_t task_2_id;
osSemaphoreId_t semaphore_id;

int buff[10]={0};

// 向buff写入数据
void task_1(void)
{
    while(1)
    {    
        printf("[Task1]try to get semaphore\n");
        osSemaphoreAcquire(semaphore_id, osWaitForever);
        printf("[Task1]get semaphore success\n");
        for(int i=0;i<sizeof(buff)/sizeof(buff[0]);i++){
            buff[i]=rand()%100;
            printf("[Task1]buff[%d]=%d\n",i,buff[i]);
        }
        osSemaphoreRelease(semaphore_id);
        printf("[Task1]release semaphore success\n");
        osDelay(1000);
    }
}

// 从buff读取数据
void task_2(void){
    while(1){
        printf("[Task2]try to get semaphore\n");
        osSemaphoreAcquire(semaphore_id, osWaitForever);
        printf("[Task2]get semaphore success\n");
        for(int i=0;i<sizeof(buff)/sizeof(buff[0]);i++){
            printf("[Task2]buff[%d]=%d\n",i,buff[i]);
        }
        osSemaphoreRelease(semaphore_id);
        printf("[Task2]release semaphore success\n");
        osDelay(1200);
    }
}

void bin_semaphore_demo()
{
    semaphore_id = osSemaphoreNew(1, 1, NULL);
    if (semaphore_id == NULL) {
        printf("Semaphore create failed!\n");
    }
    else{
        printf("[Semaphore]semaphore_id:%d\n",semaphore_id);
    }
    
    osThreadAttr_t task_1_attr={
        .name="task_1",
        .stack_size=1024*8,
        .priority=osPriorityNormal,
    };
    task_1_id=osThreadNew((osThreadFunc_t)task_1,NULL,&task_1_attr);
    if(task_1_id==NULL){
        printf("[Task1]Thread create failed!\n");
    }
    else{
        printf("[Task1]task_1_id:%d\n",task_1_id);
    }
    osThreadAttr_t task_2_attr={
        .name="task_2",
        .stack_size=1024*8,
        .priority=osPriorityNormal,
    };

    task_2_id=osThreadNew((osThreadFunc_t)task_2,NULL,&task_2_attr);
    if(task_2_id==NULL){
        printf("[Task2]Thread create failed!\n");
    }
    else{
        printf("[Task2]task_2_id:%d\n",task_2_id);
    }
}

SYS_RUN(bin_semaphore_demo);